package com.surfilter.massdata.spark.util;

import java.io.IOException;
import java.net.URI;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class CommonUtils {
	
	private static final Log log = LogFactory.getLog(CommonUtils.class);
	
	/**
	 * @param seq 序列名称
	 * @param num 集合大小
	 * @return
	 */
	public synchronized static Map<String,Long> getSeq(String tableName,long num){
		String sequenceName = tableName.toUpperCase() + "_SE";
		Map<String,Long>  map = new HashMap<String,Long>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			getSequenceName(sequenceName,conn);
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select "+sequenceName+".nextval id from (select 1 from all_objects where rownum <= "+num+")");
			List<Long> list = new ArrayList<Long>();
			while (rs.next()) {
				list.add(rs.getLong(1));
			}
			if(list != null && list.size() > 0){
				map.put("minSeq",list.get(0));
				map.put("maxSeq",list.get(list.size()-1));
			}else{
				map.put("minSeq",-1L);
				map.put("maxSeq",-1L);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(rs, stmt, conn);
		}
		return map;
	}
	
	public static String getSequenceName(String sequenceName,Connection conn) {
        String sql1 = "SELECT SEQUENCE_NAME FROM user_sequences WHERE SEQUENCE_NAME='" + sequenceName + "'";
        PreparedStatement selectStatement = null;
        PreparedStatement insertStatement = null;
        ResultSet rs = null;
        try {
            selectStatement = conn.prepareStatement(sql1);
            rs = selectStatement.executeQuery();
            if (!rs.next()) {
                String sql2 = "CREATE SEQUENCE " + sequenceName + " start with 1 increment by 1";
                insertStatement = conn.prepareStatement(sql2);
                insertStatement.execute();
            }
        } catch (SQLException e) {
        	if(log.isErrorEnabled()){
        		log.error(e.getMessage(),e);
        	}
            return null;
        }finally{
        	JdbcUtil.close(insertStatement);
        	JdbcUtil.close(selectStatement);
        	JdbcUtil.close(rs);
        }
        return sequenceName;
    }
	
	/**
	 * 创建表序列，若序列不存在
	 * @param tableName
	 */
	public static void createSeqIfNotExists(String tableName){
		Connection conn = null;
		try{
			String sequenceName = tableName.toUpperCase() + "_SE";
			conn = JdbcUtil.getConnection();
			getSequenceName(sequenceName,conn);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(conn);
		}
	}
	
	public static String valueOf(Object object){
        String str = StringUtils.trim(String.valueOf(object));
        boolean check = StringUtils.isBlank(str) || StringUtils.equals(str, "null") || StringUtils.equals(str, "undefined");
        return check ? "" : str;
	}
	
	/**
	 * 将字典表中的起始IP与结束IP存入TreeMap集合中
	 * @return
	 */
	public static TreeMap<Long,Long> getIpExtensionMap(){
		TreeMap<Long,Long> map = new TreeMap<Long,Long>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtil.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select bengin_ip_value,end_ip_value from br2002");
			while (rs.next()) {
				long beginIpValue = rs.getLong(1);
				long endIpValue = rs.getLong(2);
				
				if (map.containsKey(beginIpValue)) {
					// 判断数据库中的IP段是否有交叉
					if (map.get(beginIpValue) >= endIpValue)
						continue;
				}
				synchronized (map) {
					map.put(beginIpValue,endIpValue);
				}
			}
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(rs, stmt, conn);
		}
		return map;
	}
	
	/**
	 * 比较传入的IP是否在ipExtensionMap集合范围内，true表示在范围内
	 * @param ipExtensionMap
	 * @param ip
	 * @return
	 */
	public static boolean isExists(TreeMap<Long,Long> ipExtensionMap,String ip) {
		try{
			long value = DNSParser.ip2Long(ip);
			long endIpValue = ipExtensionMap.get(ipExtensionMap.floorKey(value));
			if(endIpValue - value < 0){
				return false;
			}
		}catch(Exception e){
			return false;
		}
		return true;
	}
	
	public static String getDomainSuffix(String domain){
		Pattern pattern = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");
		String result = "";
		try{
			String topDomain = URLUtil.getDomainName("http://" + domain);
			if(StringUtils.isNotBlank(topDomain)){
				if(pattern.matcher(topDomain).matches()){//判断是否为IP
					result =  topDomain;
				}else{
					result = topDomain.substring(topDomain.indexOf(".") + 1,topDomain.length());
				}
			}else{
				//表示域名不符合规则
				if(domain.indexOf(".") > 0){
					result = domain.substring(domain.indexOf(".") + 1,domain.length());
				}else{
					result = domain;
				}
			}
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}
		return result;
	}
	
	public static Long[] transformLongArray(String source ,String splitStr,int arrSize){
		if (StringUtils.isBlank(splitStr) && arrSize > 0){
			return null;
		}
		Long[] arrReturn = new Long[arrSize];
		if (source != null ) {
			String[] arrStr = source.split(splitStr);
			for (int i = 0 ,strSize = arrStr.length; i < arrSize ; i++) {
				if (i < strSize) {
					try {
						arrReturn[i] = Long.valueOf( arrStr[i] );
					} catch (NumberFormatException e) {
						arrReturn[i] = 0l;
					}
				} else {
					arrReturn[i] = 0l;
				}
			}
		} else {
			for (int i = 0 ; i < arrSize ; i++) {
				arrReturn[i] = 0l;
			}
		}
		return arrReturn;
	}
	
	
	public static String[] transformStringArray(String source ,String splitStr , int arrSize){
		if (StringUtils.isBlank(splitStr) && arrSize > 0){
			return null;
		}
		String[] arrReturn = new String[arrSize];
		if (source != null ) {
			String[] arrStr = source.split(splitStr);
			for (int i = 0 ,strSize = arrStr.length; i < arrSize ; i++) {
				if (i < strSize) {
					arrReturn[i] = arrStr[i];
				} else {
					arrReturn[i] = "";
				}
			}
		} else {
			for (int i = 0 ; i < arrSize ; i++) {
				arrReturn[i] = "";
			}
		}
		return arrReturn;
	}
	
	/**
	 * 判断是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		try {
			Long.parseLong(str);
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
	
	public static boolean existsPath(String dst) throws IOException{
		boolean flag=false;
		Configuration conf = new Configuration();
		FileSystem fs = null;
		try {
			fs = FileSystem.get(URI.create(dst), conf);
			flag=fs.exists(new Path(dst));
		} catch (IOException e) {
		} finally {
			if (fs != null)
				fs.close();
		}
		return flag;

	}
	
	public static boolean delPath(String dst) throws IOException{
		boolean delflag=true;
		Configuration conf = new Configuration();
		FileSystem fs = null;
		try {
			fs = FileSystem.get(URI.create(dst), conf);
			Path path=new Path(dst);
			if(fs.exists(path)){
				delflag=fs.delete(path);
			}
		} catch (IOException e) {
		} finally {
			if (fs != null)
				fs.close();
		}
		return delflag;

	}
	
	/**
	 * 删除当前任务数据
	 * @param table
	 * @param date
	 * @param bussType
	 * @param staRange
	 * @param type hour小时统计，day天统计
	 */
	public static void deleteTaskTableData(String table,Date date,String bussType,int staRange,String type){
		Connection conn = null;
		PreparedStatement ps = null;
		StringBuffer sql = new StringBuffer();
		try{
			sql.append("delete from "+table);
			sql.append(" where buss_type = '"+bussType+"'");
			sql.append("   and year = "+DateUtil.getCurrentYear(date));
			sql.append("   and month = "+DateUtil.getCurrentMonth(date));
			sql.append("   and day = "+DateUtil.getCurrentDay(date));
			if(StringUtils.equals(type,"hour")){
				sql.append("   and hour = "+DateUtil.getCurrentHour(date));
			}
			sql.append("   and sta_range = "+staRange);
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			ps.executeQuery();
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(ps,conn);
		}
	}
	
	public static void deleteTaskTable(String table,Date date,String bussType,int ssfl,String type){
		Connection conn = null;
		PreparedStatement ps = null;
		StringBuffer sql = new StringBuffer();
		try{
			sql.append("delete from "+table);
			sql.append(" where buss_type = '"+bussType+"'");
			sql.append("   and year = "+DateUtil.getCurrentYear(date));
			sql.append("   and month = "+DateUtil.getCurrentMonth(date));
			sql.append("   and day = "+DateUtil.getCurrentDay(date));
			if(StringUtils.equals(type,"hour")){
				sql.append("   and hour = "+DateUtil.getCurrentHour(date));
			}
			sql.append("   and ssfl = "+ssfl);
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			ps.executeQuery();
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(ps,conn);
		}
	}
}
